package com.xsp.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.Instant;
import java.util.Map;

/**
 * @author xsp
 * @date 2024/3/10
 * @desc
 */
public class JWTUtil {
    // 密钥
    private static final String secret = "xsp";

    public static String getToken(Map<String, String> map) {
        // 超时时间设置为7天
        Instant instant = Instant.now().plusSeconds(60 * 60 * 24 * 7);
        JWTCreator.Builder builder = JWT.create();
        // 设置payload负载值
        map.forEach(builder::withClaim);
//        设置超时时间
        builder.withExpiresAt(instant);
        return builder.sign(Algorithm.HMAC256(secret));
    }

    // 验证token
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }
}
